### Rank-Dependent Utility (RDU) and Cumulative Prospect Theory Models - Goldstein and Einhorn 1987 - Function library
## Appendix Theory: A.7
# Equations (A6) and (A7)

MaxLikeSR_RDU_GE_crossVal = function(data, sub_sample, init){
  # Leave-one-out Cross Validation (LOO CV)
  start <- Sys.time()  
  data = sample_SR(data,sub_sample)
  index = data$studentID                                                            
  data = split(data,f = index)  
  
  dfs_LOOCV = lapply(data, LOOCV_train_test_split)
  results = lapply(dfs_LOOCV, LOO_crossVal_train_predict_RDU_GE, init)
  
  b_coef = unlist(lapply(results, {function(x) mean(x[["b.coef"]])}), use.names = FALSE)
  b_coef_std = unlist(lapply(results, {function(x) sqrt(var(x[["b.coef"]]))}), use.names = FALSE)
  
  beta_coef = unlist(lapply(results, {function(x) mean(x[["beta.coef"]])}), use.names = FALSE)
  beta_coef_std = unlist(lapply(results, {function(x) sqrt(var(x[["beta.coef"]]))}), use.names = FALSE)
  
  alpha_coef = unlist(lapply(results, {function(x) mean(x[["alpha.coef"]])}), use.names = FALSE)
  alpha_coef_std = unlist(lapply(results, {function(x) sqrt(var(x[["alpha.coef"]]))}), use.names = FALSE)
  
  loss_coef = unlist(lapply(results, {function(x) mean(x[["loss.coef"]])}), use.names = FALSE)
  loss_coef_std = unlist(lapply(results, {function(x) sqrt(var(x[["loss.coef"]]))}), use.names = FALSE)
  
  score = unlist(lapply(results, {function(x) sum(x$accuracy)}), use.names = FALSE)
  results_scores = as.data.frame(cbind(studentID = unique(index), score = score, b_mean = b_coef, beta_mean = beta_coef, alpha_mean = alpha_coef, loss_mean = loss_coef,
                                       b_std = b_coef_std, beta_std = beta_coef_std, alpha_std = alpha_coef_std, loss_std = loss_coef_std))
  
  print("Rank Dependent Utility Goldstein and Einhorn (GE) - Leave-One-Out Test Accuracy Summary:")
  print(paste("Average:", mean(results_scores$score)))
  print(paste("Standard error:", sqrt(var(results_scores$score)/length(results_scores$score))))
  
  end = Sys.time()                                                                  
  timer = difftime(end,start,units = "secs")
  print(paste("Time taken for MLE algorithim and Cross-Validation:",seconds_to_period(round(timer[[1]],2))))
  return(list(estimations = results, summary = results_scores))
}



LOOCV_train_test_split = function(data){
  result = list()
  for(i in 1:length(data$qnum)){
    test_df = data[i, ]
    train_df = data[-i, ]
    result[[i]] <- list(train = train_df, test = test_df)
  }
  result
}



LOO_crossVal_train_predict_RDU_GE = function(LOO_train_test_folds, init){
  results = bind_rows(lapply(LOO_train_test_folds, LOO_train_test_RDU_GE, init))
  results
}



LOO_train_test_RDU_GE = function(train_test_dfs, init){
  train_df = train_test_dfs[["train"]]
  test_df = train_test_dfs[["test"]]
  
  results = wrapMLE_RDU_GE(train_df, init, log_lik_RDU_GE)
  results_summary = stat_sum_RDU_GE(results)
  results_summary$studentID = test_df$studentID
  
  param = list(b = results_summary$b.coef, beta = results_summary$beta.coef, alpha = results_summary$alpha.coef, loss = results_summary$loss.coef)
  test_predict_results = LOO_test_predict(test_df, param, calc_util_RDU_GE)
  results_summary = cbind(results_summary, test_qnum = test_df$qnum, test_choice = test_df$choice, test_predict_results)
  results_summary
}





LOO_test_predict = function(test_df, param, util_fun){
  lottery_data = list(l1 = list(prob = test_df[["prob.1"]], lower = test_df[["lower.1"]], upper = test_df[["upper.1"]]),
                      l2 = list(prob = test_df[["prob.2"]], lower = test_df[["lower.2"]], upper = test_df[["upper.2"]]),
                      l3 = list(prob = test_df[["prob.3"]], lower = test_df[["lower.3"]], upper = test_df[["upper.3"]]),
                      l4 = list(prob = test_df[["prob.4"]], lower = test_df[["lower.4"]], upper = test_df[["upper.4"]]),
                      l5 = list(prob = test_df[["prob.5"]], lower = test_df[["lower.5"]], upper = test_df[["upper.5"]]))
  
  lottery_utility = unlist(lapply(lottery_data, util_fun, param))
  predicted_choice = unname(which.max(lottery_utility))
  accuracy = if_else(predicted_choice == test_df$choice, 1, 0)
  list(pred_choice = predicted_choice, accuracy = accuracy)
}



calc_util_RDU_GE = function(df, param){
  w_p_RDU_GE(param[["b"]],param[["beta"]],df[["prob"]])*df[["upper"]]^param[["alpha"]] - 
    (1-w_p_RDU_GE(param[["b"]],param[["beta"]],df[["prob"]]))*param[["loss"]]*(-df[["lower"]])^param[["alpha"]]
}

w_p_RDU_GE <- function(b, beta, prob){
  (b*prob^beta)/(b*prob^beta + (1-prob)^beta)
}



wrapMLE_RDU_GE = function(data,init,logLikFun){
  RDU_maxLike_res = mle2(minuslogl = logLikFun, data = list(data=data), start = init,
                        method="L-BFGS-B", optimizer = "optim", lower = c(b=0.01, beta=0.01, alpha=0.01, loss = 1), 
                        upper = c(b=1.99, beta=1.99, alpha=1, loss = 3))
  RDU_maxLike_res
}





stat_sum_RDU_GE = function(stat){
  results = data.frame("studentID"=NA,"b.coef"=NA, "beta.coef"=NA, "alpha.coef"=NA, "loss.coef"=NA,
                       "std.b"=NA, "std.beta"=NA, "std.alpha"=NA, "std.loss"=NA,
                       "p.val.b"=NA, "p.val.beta"=NA, "p.val.alpha"=NA, "p.val.loss"=NA,
                       "logLikelihood"=NA,"AIC"=NA)
  summary = summary(stat)
  results["studentID"]     = NA
  results["b.coef"]        = summary@coef[1,1]
  results["beta.coef"]     = summary@coef[2,1]
  results["alpha.coef"]    = summary@coef[3,1]
  results["loss.coef"]     = summary@coef[4,1]
  results["std.b"]         = summary@coef[1,2]
  results["std.beta"]      = summary@coef[2,2]
  results["std.alpha"]     = summary@coef[3,2]
  results["std.loss"]      = summary@coef[4,2]
  results["p.val.b"]       = summary@coef[1,4]
  results["p.val.beta"]    = summary@coef[2,4]
  results["p.val.alpha"]   = summary@coef[3,4]
  results["p.val.loss"]    = summary@coef[4,4]
  results["logLikelihood"] = logLik(stat)
  results["AIC"]           = AIC(stat)
  return(results)
}



log_lik_RDU_GE <- function(b, beta, alpha, loss, data){
  
  #calculating denominator of likelihood of a choice
  denomCalc = function(data){
    exp(w_p_RDU_GE(b,beta,data[["prob.1"]])*data[["upper.1"]]^alpha - (1-w_p_RDU_GE(b,beta,data[["prob.1"]]))*loss*(-data[["lower.1"]])^alpha) +
    exp(w_p_RDU_GE(b,beta,data[["prob.2"]])*data[["upper.2"]]^alpha - (1-w_p_RDU_GE(b,beta,data[["prob.2"]]))*loss*(-data[["lower.2"]])^alpha) +
    exp(w_p_RDU_GE(b,beta,data[["prob.3"]])*data[["upper.3"]]^alpha - (1-w_p_RDU_GE(b,beta,data[["prob.3"]]))*loss*(-data[["lower.3"]])^alpha) +
    exp(w_p_RDU_GE(b,beta,data[["prob.4"]])*data[["upper.4"]]^alpha - (1-w_p_RDU_GE(b,beta,data[["prob.4"]]))*loss*(-data[["lower.4"]])^alpha) +
    exp(w_p_RDU_GE(b,beta,data[["prob.5"]])*data[["upper.5"]]^alpha - (1-w_p_RDU_GE(b,beta,data[["prob.5"]]))*loss*(-data[["lower.5"]])^alpha)
  }
  
  
  
  denomRes = apply(data, 1, denomCalc) #vector of denominator components for each student
  
  # calculate numerator of likelihood of a choice
  numerCalc = function(data){
    j = data[["choice"]]
    numercalc = exp(w_p_RDU_GE(b,beta,data[[13+j]])*data[[8+j]]^alpha - (1-w_p_RDU_GE(b,beta,data[[13+j]]))*loss*(-data[[3+j]])^alpha)
    numercalc
  }
  
  numerRes = apply(data, 1, numerCalc)
  
  #calculating log likelihood
  log_lik_i <-  log(numerRes/denomRes)
  
  -sum(unlist(log_lik_i))
}



sample_SR = function(data,sub_sample){
  if(sub_sample == "full"){data = data}
  if(sub_sample == "part1"){data = data %>% filter(qnum<19)}
  if(sub_sample == "part2"){data = data %>%  filter(qnum>18)}
  return(data)
}





